﻿using Mapster;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SBlogCore.Common.MapExtend
{
    public static class SblogCoreMapSetup
    {
        /// <summary>
        /// Map映射
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assemblies"></param>
        /// <returns></returns>
        public static IServiceCollection AddSblogCoreMap(this IServiceCollection services, IEnumerable<Assembly> assemblies)
        {
            TypeAdapterConfig.GlobalSettings.Default
                .GetMemberName(member => member.GetCustomAttributes(true).OfType<JsonPropertyAttribute>().FirstOrDefault()?.PropertyName);
            var types = assemblies.SelectMany(s => s.GetTypes()).Where(w => w.IsAssignableTo(typeof(ISblogCoreMap)) && !w.Equals(typeof(ISblogCoreMap)));
            foreach (var type in types)
            {
                if (!string.IsNullOrEmpty(type.FullName))
                {
                    var instance = type.Assembly.CreateInstance(type.FullName);
                    if (instance is ISblogCoreMap map)
                    {
                        map.MapDo();
                    }
                }
            }
            return services;
        }
    }
}
